﻿using Dapper.DBContext;
using Guoc.BigMall.Application.DTO;
using Guoc.BigMall.Application.Search;
using Guoc.BigMall.Application.ViewObject;
using Guoc.BigMall.Domain.Entity;
using Guoc.BigMall.Infrastructure;
using Guoc.BigMall.Infrastructure.Extension;
using Guoc.BigMall.Infrastructure.Log;
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Guoc.BigMall.Application.Facade
{
    public class DistributeOrderFacade : IDistributeOrderFacade
    {
        IDBContext _db;
        IContextFacade _context;
        ILogger _log;

        public DistributeOrderFacade(IDBContext db, IContextFacade context, ILogger log)
        {
            _db = db;
            _context = context;
            _log = log;
        }

        public IEnumerable<DistributeOrderListVo> GetList(Pager page, SearchDistributeOrder search)
        {
            IEnumerable<DistributeOrderListVo> rows;
            dynamic param = new ExpandoObject();
            string where = "";
            if (search.SaleOrderCode.NotNullOrEmpty())
            {
                where += " and  d.SaleOrderCode like @SaleOrderCode";
                param.SaleOrderCode = string.Format("{0}%", search.SaleOrderCode);
            }
            if (search.Phone.NotNullOrEmpty())
            {
                where += " and  d.MemberPhone = @Phone";
                param.Phone = search.Phone;
            }

            if (search.Code.NotNullOrEmpty())
            {
                where += " and d.Code like @Code";
                param.Code = string.Format("{0}%", search.Code);
            }

            if (search.Status.HasValue && search.Status.Value != 0)
            {
                where += " and d.Status = @Status";
                param.Status = search.Status.Value;
            }

            var sql = @"select d.Id, d.`Code`,d.SaleOrderCode,d.MemberId,d.NickName,d.MemberName,d.MemberPhone,d.ContactPhone,d.IdentityCard,d.ReferMemberId,d.CreatedOn,
d.`Status`,m.realName as ReferMemberName ,m.Phone as ReferPhone  from distributeorder d left join Member m on m.Id =d.ReferMemberId where 1=1 {0} Order By  d.Id desc LIMIT {1},{2}";
            sql = string.Format(sql, where, (page.PageIndex - 1) * page.PageSize, page.PageSize);
            rows = _db.DataBase.Query<DistributeOrderListVo>(sql, param);
            var sqlcount = string.Format(@" SELECT count(*) FROM distributeorder d left join Member m on m.Id =d.ReferMemberId  WHERE 1=1 {0} ", where);
            page.Total = this._db.DataBase.ExecuteScalar<int>(sqlcount, param);

            return rows;
        }

        /// <summary>
        ///  审核
        /// </summary>
        /// <param name="id">分销单id</param>
        /// <param name="phone">开卡人电话</param>
        /// <param name="remark">备注</param>
        public void AuditPhone(DistributeOrderAuditDto auditDto)
        {
            var order = _db.Table<DistributeOrder>().FirstOrDefault(n => n.Id == auditDto.Id);
            if (order == null) { throw new FriendlyException("分销单不存在"); }
            order.AuditPhone();
            DistributeOrderHistory auditHistory = new DistributeOrderHistory()
            {
                Createdby = _context.CurrentAccount.AccountId,
                CreatedbyName = _context.CurrentAccount.NickName,
                DistributeOrderId = order.Id,
                Remark = auditDto.Remark,
                Status = order.Status
            };
            // 校验会员关联的号码是否是一个新的
            var exists = _db.Table<DistributeMember>().Exists(n => n.Phone == order.MemberPhone || n.MemberId == order.MemberId);
            if (exists)
            {
                throw new FriendlyException(string.Format("号码{0}或会员ID={1},已经是分销会员了", order.MemberPhone, order.MemberId));
            }
            var parentMember = _db.Table<DistributeMember>().FirstOrDefault(n => n.MemberId == order.ReferMemberId);
            if (parentMember == null)
            {
                throw new FriendlyException("推荐人不是分销会员");
            }
            var dismember = new DistributeMember()
            {
                MemberId = order.MemberId,
                ParentMemberId = order.ReferMemberId,
                Phone = order.MemberPhone,
                Path = string.Format("{0}{1}#", parentMember.Path, order.MemberId),
                Level = parentMember.Level + 1
            };

            // 审核时，把通过的办卡电话和用户微信绑定
            var member = _db.Table<Member>().FirstOrDefault(n => n.Id == order.MemberId);
            if (member == null) {
                throw new FriendlyException(string.Format("会员{0},不存在！", order.MemberId));
            }

            var phoneMember= _db.Table<Member>().FirstOrDefault(n => n.Phone == order.MemberPhone);
            if (phoneMember != null && phoneMember.Id != member.Id)
            {
                // 该号码已经被其他用户使用
                throw new FriendlyException(string.Format("号码{0},已经被绑定！", order.MemberPhone));
            }

            if (!string.IsNullOrEmpty(member.Phone))
            {
                _log.Info("分销审核:会员{0},已经绑定手机！,该操作将替换原手机号{1}", order.MemberId, member.Phone);
            }

            member.Phone = order.MemberPhone;
            member.RealName = order.MemberName;
            member.SecondPhone = order.ContactPhone;
            _db.Update(member);

            _db.Insert(dismember);
            _db.Update(order);
            _db.Insert(auditHistory);
            _db.SaveChange();
        }
        /// <summary>
        ///  确认提现
        /// </summary>
        /// <param name="id"></param>
        public void ConfirmCash(DistributeOrderAuditDto auditDto)
        {
            var order = _db.Table<DistributeOrder>().FirstOrDefault(n => n.Id == auditDto.Id);
            if (order == null) { throw new FriendlyException("分销单不存在"); }
            order.ConfirmCash();
            DistributeOrderHistory auditHistory = new DistributeOrderHistory()
            {
                Createdby = _context.CurrentAccount.AccountId,
                CreatedbyName = _context.CurrentAccount.NickName,
                DistributeOrderId = order.Id,
                Remark = auditDto.Remark,
                Status = order.Status
            };

            _db.Update(order);
            _db.Insert(auditHistory);
            _db.SaveChange();

        }

        public DistributeOrderVo GetDetail(int id)
        {
            var sql = @"select d.Id, d.`Code`,d.SaleOrderCode,d.MemberId,d.MemberName,d.MemberPhone,d.NickName,d.ContactPhone,d.IdentityCard,d.ReferMemberId,d.CreatedOn,
d.`Status`,m.NickName as ReferMemberName ,m.Phone as ReferPhone
from distributeorder d left join Member m on m.Id = d.ReferMemberId where d.Id =@Id";
            var order = _db.DataBase.QuerySingle<DistributeOrderVo>(sql, new { Id = id });
            var sqlItem = @"select i.*,m.NickName,m.RealName,m.Phone,m.SecondPhone from distributeorderitem i inner join Member m on i.MemberId = m.Id where distributeorderid = @Id";
            var orderItems = _db.DataBase.Query<DistributeOrderItemVo>(sqlItem, new { Id = id });
            var sqlHistory = @"select * from distribute_order_history where distributeorderid = @Id";
            var historys = _db.DataBase.Query<DistributeOrderHistoryVo>(sqlHistory, new { Id = id });

            order.Items = orderItems;
            order.Historys = historys;
            return order;

        }

        public void PaidByFinance(int id)
        {
            var entity = _db.Table<DistributeOrder>().FirstOrDefault(disOrder => disOrder.Id == id);
            if (entity == null) {
                throw new FriendlyException("分销订单不存在");
            }

            entity.Finished();

            var items = _db.Table<DistributeOrderItem>().Where(doitem => doitem.DistributeOrderId == id).ToList();
            if (items.Count == 0) {
                throw new FriendlyException("没有分账记录");
            }
            if (!items.Any(n => n.CashStatus == MemberCashStatus.UnCash))
            {
                throw new FriendlyException("已经全部打款了");
            }

            foreach (var item in items) {
                item.CashedByFinance();
            }

            // 记录打款痕迹
           
            DistributeOrderHistory auditHistory = new DistributeOrderHistory()
            {
                Createdby = _context.CurrentAccount.AccountId,
                CreatedbyName = _context.CurrentAccount.NickName,
                DistributeOrderId = entity.Id,
                Remark = "财务手工打款",
                Status = entity.Status
            };

            _db.Insert(auditHistory);
            _db.Update(entity);
            _db.Update(items.ToArray());
            _db.SaveChange();

        }
    }
}
